/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package me.joshua.demo4j.bae.tool4j.controller;

import java.io.PrintWriter;
import java.io.StringWriter;

import me.joshua.demo4j.bae.tool4j.service.EmailNotificationService;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.baidu.bae.api.factory.BaeFactory;
import com.baidu.bae.api.fetchurl.BaeFetchurl;


/**
 *
 * @author Joshua
 */
@Controller
public class ComicController {
	
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ComicController.class);

	@Autowired
	private EmailNotificationService emailNotificationService;

	@RequestMapping(value = "/ravens", method = RequestMethod.GET)
	public String list(Model model) {

		try {
			BaeFetchurl fetchUrl = BaeFactory.getBaeFetchurl();
			String content = fetchUrl.get("http://manhua.dmzj.com/dongjingwuya/");
			Document doc = Jsoup.parse(content);
			Element element = doc.select("span.update2").first();
			String updateDate = element.text();
			StringBuilder sb = new StringBuilder();
			sb.append(updateDate);
			element = doc.select("div.cartoon_online_border ul li:last-child a").first();
			sb.append("<br />");
			String url = "http://manhua.dmzj.com" + element.attr("href");
			sb.append(url);
			sb.append(String.format("<a href=\"%s\">%s</a>", url, "TokyoRavens"));
			
			model.addAttribute("content", sb.toString());
			String subject = "Tokyo Ravens";
			String message = String.format("<a href=\"%s\">%s</a>", url, "Tokyo Ravens");
			emailNotificationService.notifyByEmail(subject, message);
			
		} catch (Exception e) {
			LOGGER.error("Fetch url failed", e);
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			model.addAttribute("message", sw.toString());
			return "/error";
		}
		
		return "/default";
	}
}
